package rpc;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class Client {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("127.0.0.1", 8080);
        OutputStream outputStream = socket.getOutputStream();
          IUserRpc rpc =  createProxy(IUserRpc.class);
        System.out.println(rpc.call());
//        outputStream.write("你好".getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        socket.shutdownOutput();
    }

    public static <T> T createProxy(Class<?> clazz){
        return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                RpcRequest request = RpcRequest.builder()
                        .paramTypes(method.getParameterTypes())
                        .params(args)
                        .className(clazz.getName())
                        .methodName(method.getName())
                        .build();
                Socket socket = new Socket("127.0.0.1", 8080);
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
                objectOutputStream.writeObject(request);
                objectOutputStream.flush();
                socket.shutdownOutput();
                return "123";
            }
        });
    }
}